package com.wewins.fota.service.export;

import com.wewins.fota.bean.bo.excel.DataSource;
import com.wewins.fota.bean.bo.excel.ExcelHeaderItem;
import com.wewins.fota.bean.bo.excel.ExportData;
import com.wewins.fota.bean.bo.excel.data.ExportFotaLog2;
import com.wewins.fota.bean.po.FotaLog;
import com.wewins.fota.common.constant.FotaCode;
import com.wewins.fota.service.ExportService;
import com.wewins.fota.service.FotaLogService;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Data
@Builder
@Slf4j
public class ExportFotaLog2Model implements ExportModel {
    private String path;

    private ExportData data;

    private ExportService service;

    @Override
    public <T> List<DataSource> fillData(List<T> data) {
        List<DataSource> excelData = new ArrayList<>();
        data.forEach(item -> {
            if (!(item instanceof FotaLog)) {
                return;
            }
            FotaLog fotaLog = (FotaLog) item;
            ExportFotaLog2 exportFotaLog = ExportFotaLog2.builder()
                    .imei(fotaLog.getImei())
                    .product(fotaLog.getProduct())
                    .fromV(fotaLog.getFromV())
                    .toV(fotaLog.getToV())
                    .userIp(fotaLog.getReqServer())
                    .installStatus(FotaCode.NONE)
                    .failCount(fotaLog.getCount())
                    .recordTime(fotaLog.getUpdateTime())
                    .build();
            if (exportFotaLog.getRecordTime() <= 0) {
                exportFotaLog.setRecordTime(fotaLog.getCreateTime());
            }
            if (service instanceof FotaLogService) {
                boolean success = ((FotaLogService) service).downloadSuccess(fotaLog);
                FotaCode mapping = success ? FotaCode.COMMON_SUCCESS : FotaCode.COMMON_FAILED;
                exportFotaLog.setInstallStatus(mapping);
                exportFotaLog.setFailCount(success ? fotaLog.getCount() - 1 : fotaLog.getCount());
            }
            excelData.add(exportFotaLog);
        });
        return excelData;
    }

    @Override
    public List<ExcelHeaderItem> getHeaders() {
        return this.getHeaders(ExportFotaLog2.class);
    }
}
